package com.stedu.security;

import cn.hutool.json.JSONUtil;
import com.stedu.bean.RespBean;
import com.stedu.service.SysUserService;
import com.stedu.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
	@Autowired
    private SysUserService sysUserService;

    //对登录成功的处理流程
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //获取当前登录的用户的用户名
        String username = authentication.getName();

        //生成JWT
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", username);

        String jwtStr = JwtUtils.generateJwt(map);

        //返回包含JWT的成功信息
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream out = response.getOutputStream();
        RespBean result = RespBean.ok("登录成功", jwtStr);

        out.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));
        out.flush();
        out.close();
    }
}